package org.example.aienglishapp.controller.word;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.aienglishapp.entity.word.ErrorWord;
import org.example.aienglishapp.entity.word.UserProgress;
import org.example.aienglishapp.service.word.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.example.aienglishapp.service.speech.userrecording.UserRecordingService.objectMapper;

@RestController
@RequestMapping("/api/word/user")
@Component("userControllerWord")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/progress")
    public ResponseEntity<Map<String, Object>> getUserProgress(@RequestParam Long userId, @RequestParam String wordBook) {
        Map<String, Object> progressData = userService.getUserProgress(userId, wordBook);
        return ResponseEntity.ok(progressData);
    }


    @CrossOrigin(origins = "http://localhost:3000")  // 允许前端应用访问
    @PostMapping("/progress")
    public ResponseEntity<?> updateUserProgress(@RequestBody UserProgress userProgress) {
        // 获取 UserProgress 中的所有必要字段
        Long userId = userProgress.getUserId();
        String wordBook = userProgress.getWordBook();
        String word = userProgress.getWord();
        Double progress = userProgress.getProgress();
        Integer timesReviewed = userProgress.getTimesReviewed();
        Timestamp lastReviewed = userProgress.getLastReviewed();
        Integer interval = userProgress.getInterval();

        // 调用 UserService 的 saveUserProgress 方法并传递所有参数
        userService.saveUserProgress(userId, wordBook, word, progress, timesReviewed, lastReviewed, interval);

        return ResponseEntity.ok("Progress updated");
    }


    // 缓存过期时间，单位为秒（例如：1小时）
    private static final long CACHE_EXPIRATION_TIME = 3600;

    // 添加错误单词

    @PostMapping("/errorWords")
    public ResponseEntity<Void> addErrorWord(@RequestBody ErrorWord errorWord) {
        try {
            // 添加错误单词到数据库
            userService.addErrorWord(errorWord);

            // 错误单词的缓存键
            String cacheKey = "errorWords:" + errorWord.getUserId();

            // 将错误单词添加到 Redis 的 Hash 中
            redisTemplate.opsForHash().put(cacheKey, errorWord.getWord(), objectMapper.writeValueAsString(errorWord));

            // 设置缓存的过期时间
            redisTemplate.expire(cacheKey, CACHE_EXPIRATION_TIME, TimeUnit.SECONDS);  // 设置过期时间为 1小时

            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 错误处理
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    // 删除错误单词
    @DeleteMapping("/errorWords")
    public ResponseEntity<Void> deleteErrorWord(@RequestParam Long userId, @RequestParam String word) {
        try {
            userService.deleteErrorWord(userId, word);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }


}